package com.it1997.it1997admin.configuration;

import com.it1997.it1997admin.pojo.Permission;
import com.it1997.it1997admin.pojo.Role;
import com.it1997.it1997admin.pojo.User;
import com.it1997.it1997admin.service.PermissionService;
import com.it1997.it1997admin.service.RoleService;
import com.it1997.it1997admin.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;


@Component
public class MyUserDetailService implements UserDetailsService {
    private Logger logger= LoggerFactory.getLogger(getClass());
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询用户信息
        User user=userService.getUserByUserName(username);

        List<Role> roles=null;
        List<Permission> permissionList=null;
        if(null!=user){
            //根据用户id查询用户角色
          roles =roleService.getRoles(user.getId());
            logger.info("role:"+roles);
            for(Role role:roles){
                // 根据角色id查询用户权限列表
                permissionList=permissionService.getPermissionList(role.getId());
            }
    List<SimpleGrantedAuthority> authorities=new ArrayList<>();
            for (Role role : roles) {
                    authorities.add(new SimpleGrantedAuthority(role.getRoleName()));
        logger.info("当前角色："+String.valueOf(new SimpleGrantedAuthority(role.getRoleName())));
    }
            return new User(user.getId(),username,user.getPassword(),roles,permissionList,authorities);
}else {
        logger.info("用户不存在！");
        throw new UsernameNotFoundException(username + "not found");
        }
    }
}
